package cn.zwx.security.example.utils;

import cn.zwx.security.example.common.enums.ResultCodeEnum;
import cn.zwx.security.example.security.handler.UserAuthAccessDeniedHandler;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @projectName:spring-boot-security-example
 * @see:cn.zwx.security.example.utils
 * @author:zhangwenxue
 * @createTime:2021/6/23 16:02
 * @version:1.0
 */
public class ResultUtil {

    private static Logger logger = LoggerFactory.getLogger(UserAuthAccessDeniedHandler.class);

    private ResultUtil(){};

    /**
     * 使用response输出JSON
     * @Author Sans
     * @CreateTime 2019/9/28 11:23
     * @Param  resultMap 数据
     * @Return void
     */
    public static void responseJson(ServletResponse response, ResultCodeEnum resultCodeEnum){
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code",resultCodeEnum.getErrorCode());
        resultMap.put("msg",resultCodeEnum.getErrorMsg());
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSON.toJSONString(resultMap));
        } catch (Exception e) {
            logger.error("【JSON输出异常】"+e);
        }finally{
            if(out!=null){
                out.flush();
                out.close();
            }
        }

    }
    /**
     * 使用response输出JSON
     * @Author Sans
     * @CreateTime 2019/9/28 11:23
     * @Param  resultMap 数据
     * @Return void
     */
    public static void responseJson(ServletResponse response, Map<String, Object> resultMap){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSON.toJSONString(resultMap));
        } catch (Exception e) {
            logger.error("【JSON输出异常】"+e);
        }finally{
            if(out!=null){
                out.flush();
                out.close();
            }
        }

    }
}
